﻿<%@ Page Language="C#" %>

<%@ Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="TarreOA.TarreOAModels" %>
<%@ Import Namespace="TarreOA.TarreOABLL" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Collections.Generic" %>

<script runat="server">
    
    private string basePath;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                this.btnAffixDel.Attributes.Add("onclick", "return openModalDialog()");
            }   
            this.LoadXML();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    /// <summary>
    /// 加载xml文件填充树节点和上级文件夹下拉列表框
    /// </summary>
    /// <param name="type"></param>
    private XmlDocument document = new XmlDocument();
    protected void LoadXML()
    {
        User curLoginUser = (User)Session["user"];
        if (FindConfigurationPath.instance().UserFileCabinetPaths[curLoginUser.LoginName] == null)
        {
            FindConfigurationPath.instance().AddUserFileCabinetPaths(curLoginUser.LoginName, curLoginUser.LoginName); 
        }
        //string folderPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName;
        //string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
        //    + "\\" + curLoginUser.LoginName + ".xml"; 
        string folderPath = FindConfigurationPath.instance().UserFileCabinetPaths[curLoginUser.LoginName].ToString();
        basePath = folderPath; 
        string dirPath = FindConfigurationPath.instance().UserFileCabinetPaths[curLoginUser.LoginName] + "\\"
            + curLoginUser.LoginName + ".xml";  
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath); 
        }  
        Treeview1.Nodes.Clear();
        this.DropDownList1.Items.Clear();
        TreeNode rootNode = new TreeNode("我的根目录", "document");
        rootNode.ImageUrl = "../images/treeCollapse.png"; 
        rootNode.SelectAction = TreeNodeSelectAction.Expand;
        Treeview1.Nodes.Add(rootNode);
        Treeview1.ExpandAll();
        this.DropDownList1.Items.Add(new ListItem(rootNode.Text, rootNode.Value));
        if (!File.Exists(dirPath))
        {
            using (StreamWriter sw = File.CreateText(dirPath))
            {
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                sw.WriteLine("<document>");
                sw.WriteLine("</document>");
            }
        }
        else
        {
            document.Load(dirPath);
            showNode(document, rootNode);
        }
    }
    private void showNode(XmlNode node, TreeNode tNode)
    {
        bool state = false;
        TreeNode tn = new TreeNode();
        if (node.NodeType == XmlNodeType.Element)
        {
            if (node.Attributes.Count > 0)
            {
                state = true;
                tn.Text = node.Attributes["name"].Value;
                tn.Value = node.Attributes["createTime"].Value;
                tn.ImageUrl = "../images/treeCollapse.png";
                tNode.ChildNodes.Add(tn);
                this.DropDownList1.Items.Add(new ListItem(tn.Text, tn.Value));
            }
        }
        if (node.HasChildNodes)
        {
            tn.SelectAction = TreeNodeSelectAction.Expand;
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                if (state)
                {
                    showNode(node.ChildNodes[i], tn);
                }
                else
                {
                    showNode(node.ChildNodes[i], tNode);
                }
            }
        }
    }
    ///////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// 删除xml文件的指定节点
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private XmlDocument doc = new XmlDocument();
    protected void delXmlNode()
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
            + "\\" + curLoginUser.LoginName + ".xml"; 
        doc.Load(dirPath);
        showXMLNode(doc);
    }
    protected void showXMLNode(XmlNode node)
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
            + "\\" + curLoginUser.LoginName + ".xml"; 
        if (node.NodeType == XmlNodeType.Element)
        {
            if (node.Attributes.Count > 0)
            {
                string nodeValue = node.Attributes["createTime"].Value; 
                if (nodeValue.Equals(this.hidSelectedValue.Value))
                {
                    node.ParentNode.RemoveChild(node);
                    doc.Save(dirPath);
                }
            }
        }
        if (node.HasChildNodes)
        {
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                showXMLNode(node.ChildNodes[i]);
            }
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// 更改指定节点的name属性
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private XmlDocument docUpdate = new XmlDocument();
    protected void updateXmlNode()
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
            + "\\" + curLoginUser.LoginName + ".xml";    
        docUpdate.Load(dirPath);
        this.showXMLNodeToUpdate(docUpdate);
    }

    protected void showXMLNodeToUpdate(XmlNode node)
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
            + "\\" + curLoginUser.LoginName + ".xml"; 
        if (node.NodeType == XmlNodeType.Element)
        {
            if (node.Attributes.Count > 0)
            {
                string nodeValue = node.Attributes["createTime"].Value; 
                if (nodeValue.Equals(this.hidUpdateFolderValue.Value))
                {
                    node.Attributes["name"].Value = this.txtNewName.Text;
                    docUpdate.Save(dirPath);
                }
            }
        }
        if (node.HasChildNodes)
        {
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                showXMLNodeToUpdate(node.ChildNodes[i]);
            }
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////

    /// <summary>
    /// 添加元素到指定节点
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private XmlDocument docForAdd = new XmlDocument();
    protected void addXmlNode()
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName 
            + "\\" + curLoginUser.LoginName + ".xml"; 
        //docForAdd.Load(Server.MapPath("~/User/XMLFile.xml"));
        docForAdd.Load(dirPath); 
        if ("document".Equals(Request.Params.GetValues("DropDownList1")[0]))
        {
            XmlAttribute attrName = docForAdd.CreateAttribute("name");
            attrName.Value = this.TextBox1.Text;
            XmlAttribute attrCreateTime = docForAdd.CreateAttribute("createTime");
            attrCreateTime.Value = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
                + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            XmlNode xn = docForAdd.CreateNode(XmlNodeType.Element, "root", "");
            xn.Attributes.Append(attrName);
            xn.Attributes.Append(attrCreateTime);
            docForAdd.DocumentElement.AppendChild(xn);
            docForAdd.Save(dirPath);
            this.TextBox1.Text = "";
        }
        else
        {
            this.showXMLNodeToAdd(docForAdd);
        }
    }
    protected void showXMLNodeToAdd(XmlNode node)
    {
        User curLoginUser = (User)Session["user"];
        string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName
            + "\\" + curLoginUser.LoginName + ".xml"; 
        if (node.NodeType == XmlNodeType.Element)
        {
            if (node.Attributes.Count > 0)
            {
                string nodeValue = node.Attributes["createTime"].Value; 
                if (nodeValue.Equals(Request.Params.GetValues("DropDownList1")[0]))
                {
                    if (!"".Equals(this.TextBox1.Text))
                    {
                        XmlAttribute attrName = docForAdd.CreateAttribute("name");
                        attrName.Value = this.TextBox1.Text;
                        XmlAttribute attrCreateTime = docForAdd.CreateAttribute("createTime");
                        attrCreateTime.Value = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
                            + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                        XmlNode xn = docForAdd.CreateNode(XmlNodeType.Element, "root", "");
                        xn.Attributes.Append(attrName);
                        xn.Attributes.Append(attrCreateTime);
                        node.AppendChild(xn);
                        docForAdd.Save(dirPath);
                        this.TextBox1.Text = "";
                    }
                }
            }
        }
        if (node.HasChildNodes)
        {
            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                showXMLNodeToAdd(node.ChildNodes[i]);
            }
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    protected void Treeview1_SelectedNodeChanged(object sender, EventArgs e)
    {
        User curLoginUser = (User)Session["user"];
        if (Treeview1.SelectedNode != null)
        {
            for (int i = 0; i < this.DropDownList1.Items.Count; i++)
            {
                if (this.Treeview1.SelectedNode.Value.Equals(DropDownList1.Items[i].Value))
                {
                    DropDownList1.Items[i].Selected = true;
                    this.hidSelectedValue.Value = Treeview1.SelectedNode.Value;
                    this.lblFilePlace.Text = this.DropDownList1.Items[i].Text;  
                }
            }
            UserFileCabinettbService userFileCabinettbService = new UserFileCabinettbService();
            List<UserFileCabinettb> list = userFileCabinettbService.findByFilePathAndUserLoginName(Treeview1.SelectedNode.Value, curLoginUser.LoginName);
            if (list != null && list.Count > 0)
            {
                foreach (UserFileCabinettb userFileCabinet in list)
                {
                    TreeNode node = new TreeNode(userFileCabinet.FileTitle, userFileCabinet.FileId.ToString());
                    node.ImageUrl = "../images/FileCabinetFile.png";
                    node.NavigateUrl = "javascript:openFileCabinetInfoDialog(" + node.Value + ")";
                    Treeview1.SelectedNode.ChildNodes.Add(node); 
                } 
            }   
            this.txtSourceName.Text = Treeview1.SelectedNode.Text;
            this.hidUpdateFolderValue.Value = Treeview1.SelectedNode.Value;
            Treeview1.ExpandAll();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        this.addXmlNode();
        LoadXML();
        //this.lblFilePlace.Text = "我的根目录"; 
        Treeview1.ExpandAll();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        this.txtNewName.Text = "";
        this.txtSourceName.Text = "";
        this.delXmlNode();
        this.LoadXML();
        this.lblFilePlace.Text = "我的根目录";
        this.hidUpdateFolderValue.Value = "document";
        this.lbxFileList.Items.Clear(); 
        Treeview1.ExpandAll();
    }

    protected void btnChange_Click(object sender, EventArgs e)
    {
        this.updateXmlNode();
        this.LoadXML();
        //this.lblFilePlace.Text = "我的根目录";
        string str = this.hidUpdateFolderValue.Value;
        //string strNew = this.txtNewName.Text + str.Substring(str.IndexOf("_"));
        //this.hidUpdateFolderValue.Value = strNew;
        this.lblFilePlace.Text = this.txtNewName.Text;    
        this.txtSourceName.Text = "";
        Treeview1.ExpandAll();
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        User curLoginUser = (User)Session["user"];
        //string dirPath = ConfigurationManager.ConnectionStrings["UserFileCabinetPath"].ToString() + curLoginUser.LoginName;
        string dirPath = basePath;
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        if ("document".Equals(this.hidUpdateFolderValue.Value))
        {
        }  
        else if (FileUpload1.HasFile)
        {
            string filePath = dirPath + "\\" + this.hidUpdateFolderValue.Value + "_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
                + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()
                    + "_" + FileUpload1.FileName; 
            FileUpload1.SaveAs(filePath);
            this.lbxFileList.Items.Add(new ListItem(FileUpload1.FileName, filePath.Replace(basePath, "")));
        }
        Treeview1.ExpandAll(); 
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < this.lbxFileList.Items.Count; i++)
        {
            if (lbxFileList.Items[i].Selected)
            {
                if (File.Exists(lbxFileList.Items[i].Value))
                {
                    File.Delete(lbxFileList.Items[i].Value);
                    lbxFileList.Items.Remove(lbxFileList.Items[i]);
                    i--; 
                }
            }               
        }  
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        User curLoginUser = (User)Session["user"];
        string fileTilte = this.TextBox2.Text;
        string fileContent = this.FreeTextBox1.Text;
        UserFileCabinettbService userFileCabinettbService = new UserFileCabinettbService();
        UserFileCabinetUploadFiletbService userFileCabinetUploadFiletbService = new UserFileCabinetUploadFiletbService(); 
        int fid = userFileCabinettbService.saveUserFileCabinetInfo(fileTilte, fileContent, this.hidUpdateFolderValue.Value, DateTime.Now
            , curLoginUser.LoginName);
        for (int i = 0; i < this.lbxFileList.Items.Count; i++)
        {
            string fileName = lbxFileList.Items[i].Text;
            string filePath = lbxFileList.Items[i].Value;
            userFileCabinetUploadFiletbService.saveUploadFileInfo(fileName, filePath, DateTime.Now, fid);
        }
        this.lbxFileList.Items.Clear(); 
    }

    protected void btnAffixDel_Click(object sender, EventArgs e)
    {
        string fids = this.hidWillDelFids.Value;
        if (fids != null && !"".Equals(fids) && !"undefined".Equals(fids))
        {
            UserFileCabinetUploadFiletbService ufcufs = new UserFileCabinetUploadFiletbService(); 
            string[] fs = fids.Split(',');
            for (int i = 0; i < fs.Length; i++)
            {
                if (fs[i] != null && !"".Equals(fs[i]))
                {
                    File.Delete((ufcufs.findByFileId(int.Parse(fs[i])).FilePath));
                    ufcufs.delAffixFileInfo(int.Parse(fs[i])); 
                } 
            }    
        }   
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
    <script type="text/javascript" src="../js/FileCabinet.js"></script>
</head>
<body leftmargin="0" topmargin="0">
    <form id="form1" runat="server">
        <div>
            <table style="width: 548px" align="center">
                <tr>
                    <td style="width: 3px; height: 619px;" valign="top">
                        <asp:Panel ID="Panel2" runat="server" Height="625px" Width="180px" BorderStyle="Inset"
                            ScrollBars="Auto">
                            <asp:TreeView ID="Treeview1" runat="server" Height="649px" OnSelectedNodeChanged="Treeview1_SelectedNodeChanged"
                                Width="192px" ImageSet="Arrows" ShowLines="True">
                                <ParentNodeStyle Font-Bold="False" />
                                <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
                                <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px"
                                    VerticalPadding="0px" />
                                <NodeStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Black" HorizontalPadding="5px"
                                    NodeSpacing="0px" VerticalPadding="0px" />
                            </asp:TreeView>
                        </asp:Panel>
                    </td>
                    <td valign="top" style="height: 619px">
                        <table style="width: 515px; height: 169px">
                            <tr>
                                <td style="width: 5218px">
                                    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Smaller" Text="创建文件夹"
                                        Width="120px" ForeColor="Teal"></asp:Label></td>
                                <td style="width: 277px">
                                    <asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="Smaller" Text="更改文件夹"
                                        Width="132px" ForeColor="Teal"></asp:Label></td>
                            </tr>
                            <tr>
                                <td style="width: 5218px; height: 57px">
                                    <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Size="Smaller" Text="文件夹名称："
                                        Width="98px"></asp:Label><br />
                                    <asp:TextBox ID="TextBox1" runat="server" BackColor="#FFFFC0" Width="225px"></asp:TextBox><br />
                                    <asp:Label ID="Label3" runat="server" Font-Bold="True" Font-Size="Smaller" Text="上级文件夹："
                                        Width="98px"></asp:Label><br />
                                    <asp:DropDownList ID="DropDownList1" runat="server" BackColor="#FFFFC0" Width="229px">
                                    </asp:DropDownList>&nbsp;
                                </td>
                                <td style="width: 277px; height: 57px">
                                    <asp:Label ID="Label5" runat="server" Font-Bold="True" Font-Size="Smaller" Text="原文件夹名称："
                                        Width="98px"></asp:Label><br />
                                    <asp:TextBox ID="txtSourceName" runat="server" BackColor="#E0E0E0" ReadOnly="True"
                                        Width="225px"></asp:TextBox><br />
                                    <asp:Label ID="Label6" runat="server" Font-Bold="True" Font-Size="Smaller" Text="新文件夹名称："
                                        Width="98px"></asp:Label><br />
                                    <asp:TextBox ID="txtNewName" runat="server" BackColor="#FFFFC0" Width="225px"></asp:TextBox></td>
                            </tr>
                            <tr>
                                <td style="width: 5218px">
                                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" OnClientClick="return checkCreateFolder('TextBox1')"
                                        Text="创建" Width="61px" />
                                </td>
                                <td style="width: 277px">
                                    <asp:Button ID="btnChange" runat="server" OnClick="btnChange_Click" OnClientClick="return checkUpdateFolder('txtSourceName','txtNewName')"
                                        Text="更改" Width="69px" />
                                    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" OnClientClick="return checkDelFolder('txtSourceName')"
                                        Text="删除" Width="64px" /></td>
                            </tr>
                            <tr>
                                <td style="width: 5218px; height: 21px">
                                </td>
                                <td style="width: 277px; height: 21px;">
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:Label ID="Label7" runat="server" Font-Bold="True" Font-Size="Smaller" Text="新建文件         位置:"
                                        Width="100px" ForeColor="Teal"></asp:Label>
                                    <asp:Label ID="lblFilePlace" runat="server" Font-Bold="True" Font-Size="Smaller"
                                        Width="419px" ForeColor="Purple">我的根目录</asp:Label></td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 11px" valign="middle">
                                    <asp:Label ID="Label8" runat="server" Font-Bold="True" Font-Size="Smaller" Text="文件标题:"
                                        Width="60px"></asp:Label>
                                    <asp:TextBox ID="TextBox2" runat="server" Width="407px" BackColor="#FFFFC0"></asp:TextBox></td>
                            </tr>
                            <tr>
                                <td colspan="2" style="height: 222px" valign="top">
                                    <asp:Label ID="Label9" runat="server" Font-Bold="True" Font-Size="Smaller" Text="文件描述和上传附件:"
                                        Width="473px"></asp:Label>
                                    <asp:FileUpload ID="FileUpload1" runat="server" Width="478px" BackColor="#FFFFC0" />
                                    <asp:Button ID="btnUpload" runat="server" Height="23px" OnClick="btnUpload_Click"
                                        OnClientClick="return checkUploadFile('FileUpload1','hidUpdateFolderValue')"
                                        Text="上传" Width="68px" /><br />
                                    <asp:ListBox ID="lbxFileList" runat="server" Width="477px" BackColor="#FFFFC0" SelectionMode="Multiple"></asp:ListBox>
                                    <asp:Button ID="btnDel" runat="server" OnClientClick="return checkDelAffixFile('lbxFileList')"
                                        Text="删除" Width="68px" OnClick="btnDel_Click" /><br />
                                    <FTB:FreeTextBox ID="FreeTextBox1" runat="server" Height="200px" Width="550px">
                                    </FTB:FreeTextBox>
                                    <asp:Button ID="btnSubmit" runat="server" OnClientClick="return checkSubmitFileInfo('TextBox2')"
                                        Text="提交" Width="95px" OnClick="btnSubmit_Click" />
                                    <asp:Button ID="btnAffixDel" runat="server" OnClick="btnAffixDel_Click" Text="Button"
                                        Visible="True" Width="0px" Height="0px" />
                                    <input id="hidFcid" type="hidden" />
                                    <input id="hidWillDelFids" runat="server" type="hidden" /></td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
            <input id="hidSelectedValue" runat="server" style="width: 71px" type="hidden" />
            <input id="hidUpdateFolderValue" runat="server" style="width: 71px" type="hidden" value="document" /></div>
    </form>
</body>
</html>
